/*
 * @Author: DUST
 * @Date: 2023-05-16 16:10:53
 * @LastEditors: DUST
 * @LastEditTime: 2023-06-09 11:25:07
 * @FilePath: \vite-project\src\utils\defaultImg.ts
 * @Description: 
 * undefined
 */
/**
 * 检测图片是否存在
 * @param url
 */
const imageIsExist = function(url: string) {
  return new Promise(resolve => {
    let img: any = new Image();
    img.src = url;
    img.onload = function() {
      if (this.complete == true) {
        resolve(true);
        img = null;
      }
    };
    img.onerror = function() {
      resolve(false);
      img = null;
      // console.log("还会走下来");
    };
  });
};
const defaultImg = async function(el: any, binding: any) {
  //指令名称为：v-default-img
  const imgURL = el.src; //获取图片地址
  const defaultURL = binding.value;
  if (imgURL) {
    const exist = await imageIsExist(imgURL);
    if (exist) el.setAttribute("src", imgURL);
    else el.setAttribute("src", defaultURL);
  } else el.setAttribute("src", defaultURL);
};

export default defaultImg;
